<?php


namespace app\model;


use Exception;
use think\exception\DbException;

class AppUserWallet extends Base
{

    public static function get($data = null, $with = [], $cache = false)
    {
        $model = parent::get($data, $with, $cache);
        if(!$model){
            parent::create($data);
            $model = parent::get($data, $with, $cache);
        }
        return $model;
    }

    //更新余额
    /**
     * @param $uid
     * @param $tid
     * @param $money
     * @return bool
     * @throws Exception
     */
    public function updateMoney($uid, $tid, $money)
    {
        $walletModel = AppUserWallet::get(['tid' => $tid, 'uid' => $uid]);
        if ($walletModel) {
            $walletModel->setAttr('money', ($walletModel->money + $money));
            $updateWalletDone = $walletModel->allowField(true)->save();
            if (!$updateWalletDone) {
                throw new DbException('操作增加余额失败');
            }
        } else {
            $done = AppUserWallet::create(['tid' => $tid, 'uid' => $uid, 'money' => $money]);
            if (!$done) {
                throw new DbException('操作增加余额失败');
            }
        }
        return true;
    }

    //更新收入
    /**
     * @param $uid
     * @param $tid
     * @param $money
     * @return bool
     * @throws Exception
     */
    public function updateIncome($uid, $tid, $money)
    {
        $walletModel = AppUserWallet::get(['tid' => $tid, 'uid' => $uid]);
        if ($walletModel) {
            $walletModel->setAttr('income', ($walletModel->income + $money));
            $updateWalletDone = $walletModel->allowField(true)->save();
            if (!$updateWalletDone) {
                throw new DbException('操作增加收入失败');
            }
        } else {
            $done = AppUserWallet::create(['tid' => $tid, 'uid' => $uid, 'income' => $money]);
            if (!$done) {
                throw new DbException('操作增加收入失败');
            }
        }
        return true;
    }
}